package 一对一通信;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class SocketThread {

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		DatagramSocket dsSend=new DatagramSocket();
		DatagramSocket dsReceive=new DatagramSocket(9090);
		SendDemo1 sd=new SendDemo1(dsSend);
		ReceiveDemo1 rd=new ReceiveDemo1(dsReceive);
		Thread t1=new Thread(sd);
		Thread t2=new Thread(rd);
		t1.start();
		t2.start();
	}

}
class SendDemo1 implements Runnable {
	DatagramSocket ds;
	public SendDemo1(DatagramSocket ds){
		this.ds=ds;
	}
	public void run(){
		try {
			System.out.println("Please write down...");
			while(true){
				BufferedReader br = new BufferedReader(new InputStreamReader(
						System.in));
				String sen=br.readLine();
				if(sen=="886") {
					break;
				}
				byte[] data = sen.getBytes("GBK");
				DatagramPacket dp = new DatagramPacket(data, data.length,
						InetAddress.getByName("192.168.11.29"), 9090);
				ds.send(dp);
			}
			ds.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}
class ReceiveDemo1 implements Runnable {
	DatagramSocket ds;
	public ReceiveDemo1(DatagramSocket ds){
		this.ds=ds;
	}
	public void run(){
		try {
			while(true){
				byte[]data=new byte[1024];
				DatagramPacket dp=new DatagramPacket(data, data.length);
				ds.receive(dp);
				byte[] data2 = dp.getData();
				String str=new String(data2,0,dp.getLength());
				if(str=="886") {
					break;
				}
				String name = dp.getAddress().getHostName();
				String ip = dp.getAddress().getHostAddress();
				System.out.println(name+"-"+ip+"-"+str);
			}
			ds.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}